package com.wanjian.sak;

import android.app.Application;
import android.view.InputEvent;
import android.view.View;
import android.view.ViewRootImpl;

import com.wanjian.sak.config.Config;
import com.wanjian.sak.layer.LayerRoot;
import com.wanjian.sak.system.input.InputEventListener;
import com.wanjian.sak.system.input.InputEventReceiverCompact;
import com.wanjian.sak.system.window.compact.BaseWindowRootViewCompactV19Impl;
import com.wanjian.sak.system.window.compact.IWindowChangeListener;
import com.wanjian.sak.utils.OptionPanelUtils;
import com.wanjian.sak.view.SAKContainerView;


final class Scaffold {
    private static Application sApplication;

    public void start(final Application application, final Config config) {
        sApplication = application;

        BaseWindowRootViewCompactV19Impl baseWindowRootViewCompat = new BaseWindowRootViewCompactV19Impl();
        baseWindowRootViewCompat.addWindowChangeListener(new IWindowChangeListener() {

            @Override
            public void onAddWindow(final ViewRootImpl viewRootImpl, final View view) {
                if (view instanceof SAKContainerView) {
                    return;
                }

                view.post(new Runnable() {
                    @Override
                    public void run() {
                        LayerRoot layerRoot = LayerRoot.create(config, viewRootImpl, view, sApplication);
                        OptionPanelUtils.enableIfNeeded(layerRoot);

                        observerInputEvent(layerRoot, viewRootImpl, view);
                        OptionPanelUtils.addLayerRoot(layerRoot);
                    }
                });
            }

            @Override
            public void onRemoveWindow(ViewRootImpl viewRootImpl, View view) {

            }
        });
        OptionPanelUtils.showEntrance(application, config);
    }


    private void observerInputEvent(final LayerRoot layerRoot, final ViewRootImpl viewRootImpl, final View rootView) {
        InputEventReceiverCompact.get(viewRootImpl, new InputEventListener() {
            @Override
            public boolean onBeforeInputEvent(InputEvent inputEvent) {
                return layerRoot.beforeInputEvent(rootView, inputEvent);
            }

            @Override
            public void onAfterInputEvent(InputEvent inputEvent) {
                layerRoot.afterInputEvent(rootView, inputEvent);
            }
        });
    }


}
